<?php

namespace app\db\model;

use think\Db;
use think\Model;

class DbUsercareRole extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dbName     = 'db_usercare_role';
    # --------------------------------- 查询类接口 START------------------------------------
    
    
    # ---------------------------------- 查询类接口 END-------------------------------------
    /**
     * 初始化数据库角色
     * @param [type] $database_id 数据库id
     *               $role_rank   需要查询的角色等级
     * @author MSQ    2021-8-3
     */
    public function getDatabaseRole($database_id = 0,$role_rank = [])
    {
        $databaseInfo = model('DbDatabase')->getDetails($database_id);
        # 子库调用 获取总库角色
        if ($databaseInfo['parent_id']) $database_id = $databaseInfo['parent_id'];
        
        $where = [
            'database_id' => $database_id,
            'role_status' => 1,
        ];
        if ($role_rank) $where['role_rank'] = ['IN',$role_rank];

        $roleList = db($this->dbName)->where($where)->select();
        return $roleList;
    }
    
    # ------------------------------- 数据处理类接口 START ----------------------------------
    
    /**
     * 初始化数据库角色
     * @param [type] $database_id 数据库id
     * @author MSQ    2021-8-3
     */
    public function initRoleForCreatDb($database_id = 0,$usercare_id = 0)
    {
    	if (!$database_id) return false;
        # 仅允许总库初始化权限
        $parent_id = model('DbDatabase')->getDetails($database_id,'parent_id');
        if ($parent_id) return true;

        # 系统默认角色
        $systemRole = db($this->dbName)->where(['role_status' => 1,'database_id' => 0])->select();
        if (!$systemRole) return true;
        foreach ($systemRole as $key => $value) {
            $roleData[] = [
                'role_name'   => $value['role_name'],
                'role_rank'   => $value['role_rank'],
                'role_note'   => $value['role_note'],
                'database_id' => $database_id,
                'usercare_id' => $usercare_id,
                'auth_ids'    => $value['auth_ids'],
            ];
        }
        // $res = $this->saveAll($roleData);
        $res = $this->setAttr('id',null)->isUpdate(false)->saveAll($roleData);
        if (!$res) return false;
        return true;
    }
    # --------------------------------- 数据处理类接口 END ----------------------------------
    

}
